<?php

namespace App\Modules\Admin\Controllers;


use App\Models\District;
use App\Models\Resource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DistrictController extends Controller
{
    public function index(Request $request)
    {
        $parentid = (int)$request->parentid;
        $areas    = District::with('parent')->where('parentid', $parentid)->orderBy('order')->paginate(50);
        return view('admin::district.index', ['areas' => $areas, 'parentid' => $parentid]);
    }

    public function get()
    {
        return response()->json(Resource::query()->get());
    }

    public function first(Request $request)
    {
        $id = $request->id;
        return response()->json(District::find($id));
    }

    public function getByParent(Request $request)
    {
        $info = District::where('parentid',$request->parentid)->get();
        return response()->json($info);
    }

    public function save(Request $request)
    {
        $params = $request->all();
        $rule   = [
            'name' => 'required'
        ];
        Validator::make($params, $rule)->validate();
        if (isset($params['id'])) {
            District::query()->where('id', $params['id'])->update($params);
        } else {
            District::create($params);
        }
    }

    public function form(Request $request)
    {
        $id       = $request->id;
        $district = null;
        $parentid = null;
        if (isset($id)) {
            $district = District::find($id);
        } else {
            $parentid = $request->input('parentid');
        }
        return view('admin::district.form', ['id' => $id, 'district' => $district, 'parentid' => $parentid]);
    }

    public function delete(Request $request)
    {
        District::destroy($request->input('id'));
    }
}
